#include "MaSocketServeur.h"
#include <iostream>

MaSocketServeur::MaSocketServeur(QTcpSocket *socket, SessionClientSurServeur* parent) : MaSocket(socket, parent)
{
    connect(this, SIGNAL(sig_demandeConnexion(QString,QString)), parent, SLOT(demandeConnexion(QString,QString)));
    connect(this, SIGNAL(sig_demandeConnexion(QString)), parent, SLOT(demandeConnexion(QString)));
    connect(this, SIGNAL(envoyerATous(QString)), parent, SLOT(envoyerATous(QString)));
    connect(socket, SIGNAL(disconnected()), parent, SLOT(deconnexionClient()));
}

void MaSocketServeur::traitementMessage(quint8 typeApplication, quint8 typeMessage, QByteArray contenu)
{
    QDataStream in(contenu);
    switch(typeApplication)
    {
    case NOYAU:
        {
            switch(typeMessage)
            {
            case DEMANDE_CONNEXION:
                {
                    QString pseudo;
                    in >> pseudo;
                    emit sig_demandeConnexion(pseudo);
                    break;
                }
            case DEMANDE_CONNEXION_PASS:
                {
                    QStringList list;
                    QString message, pseudo, pass;
                    in >> message;
                    list = message.split(" ");
                    if(list.empty())
                    {
                        pseudo = "null";
                        pass = "";
                    }
                    else
                    {
                        pseudo = list.first();
                        list.removeFirst();
                        if(list.empty()) pass = "";
                        else pass = list.first();
                    }
                    emit sig_demandeConnexion(pseudo, pass);
                    break;
                }
            }
            break;
        }
    case CHAT:
        {
            switch(typeMessage)
            {
            case ENVOYER_A_TOUS:
                {
                    QString message;
                    in >> message;
                    emit envoyerATous(message);
                    break;
                }
            }
            break;
        }
    }

}
